<template>
  <van-nav-bar
      title="发表帖子详情"
      left-arrow
      @click-left="$router.back()"
  />

  <div class="post-header">
    <van-cell v-for="postPage in postPageDetails" :key="postPage.id">
      <div class="post-item">
        <img :src="postPage.url" alt="cover" class="cover-image"/>
        <div class="post-info">
          <img :src="postPage.avatar" alt="avatar" class="avatar"/>
          <span class="nickname">{{ postPage.nickname }}</span>
          <div class="post-content">
            <h2 class="title">{{ postPage.title }}</h2>
            <p>{{ postPage.content }}</p>
          </div>
        </div>
      </div>
    </van-cell>
  </div>
  <div class="post-actions">
    <!--      <van-icon name="like-o" class="{ 'liked-icon': isLiked }" @click="likePost">点赞 {{ postPage.likeCount }}</van-icon>-->
    <van-icon :name="isLiked ? 'like' : 'like-o'" :class="{ 'liked-icon': isLiked }" @click="likePost">点赞
      {{ postPage.likeCount }}
    </van-icon>
  </div>


  <!--评论区-->

    <!--    显示数量-->
    <p>共{{ comments.length }}条评论</p>

    <!--  获取评论列表-->
      <div v-for="comment in comments" :key="comment.id" class="comment">
        <div class="comment-info">


          <img :src="comment.avatar" alt="avatar" class="avatar"/>
          <span class="nickname">{{ comment.nickname }}</span>
          <span class="create-time">{{ formatDate(comment.createTime) }}</span>

        </div>


        <p class="content">{{ comment.content }}</p>

      </div>



    <!--  提交评论-->


  <div class="comment-form">
    <van-field v-model="commentContent.content" placeholder="写下你的评论..." class="comment-input"/>
    <van-button type="primary" @click="submitComment" class="submit-button">提交</van-button>
  </div>


</template>

<script setup>
import {ref, onMounted, watch} from 'vue';
import {useRoute} from 'vue-router';
import {get, post} from "../../util/request.js";
import {Toast} from "vant";

const route = useRoute();
const postPageId = route.params.postPageId;

const postPageDetails = ref([]);

const comments = ref([]);
const commentContent = ref({

  content: '',

});


const postPage = ref({
  // 其他属性...
  likeCount: 0,
  // 其他属性...
});
const isLiked = ref(false);

onMounted(() => {
  // 发起 GET 请求到指定的 URL
  get(`life/postPage/${postPageId}`)
      .then(response => {
        console.log("response响应：", response);
        // 检查响应状态码
        if (Array.isArray(response) && response.length > 0) {
          postPageDetails.value = response;
          console.log("response的data数据：", response);
        } else {
          console.error('Unexpected API Response Structure:', response);
        }
      })
      .catch(error => {
        // 提供更详细的错误信息
        if (error.response) {
          // 服务器返回了状态码但没有在 2xx 范围内
          console.error("Response error:", error.response, error.response.data);
        } else if (error.request) {
          // 请求已经发出，但没有收到响应
          console.error("Request error:", error.request);
        } else {
          // 在设置请求时发生了一些错误
          console.error("Unknown error:", error.message);
        }
      });
});
const likePost = () => {
  post(`life/postPage/${postPageId}/like`)
      .then(() => {
        postPage.value.likeCount += 1;
        isLiked.value = true;
      })
      .catch(error => {
        console.error("Failed to like post page:", error);
      });
};
const url = `life/postPage/${postPageId}/commentList`;

// 获取评论列表
const fetchComments = () => {
  get(url)
      .then(response => {
        if (response.code === 0) {
          comments.value = response.data;
          console.log(response);
        }
      })
      .catch(error => {
        console.error('Error fetching comments:', error);
        Toast.error('获取评论失败');
      });
};

// 提交评论
// const submitComment = () => {
//   if (commentContent.value.trim()) {
//     post(`life/postPage/${postPageId}/addComment`, { content: commentContent.value })
//         .then(() => {
//           commentContent.value = '';
//           return get(`life/postPage/${postPageId}`);
//         })
//         .then(response => {
//           comments.value = response.data.comments;
//         })
//         .catch(error => {
//           console.error("Failed to submit comment or fetch updated comments:", error);
//         });
//   }
// };


const submitComment = () => {
  const content = commentContent.value.content.trim()
  if (!content) {
    Toast.error('评论内容不能为空');
    return;
  }
  post(`life/postPage/${postPageId}/addComment`, {content})
      .then(response => {
        // 检查后端返回的数据类型是否符合预期
        if (response.code === 0) {

            // 清空评论框内容
            commentContent.value.content = '';
            Toast.success('评论提交成功');
            // 成功后重新获取评论列表
             fetchComments();
          } else {
            Toast.error('提交评论失败：' + response.data.msg);

          }

      })
      .catch(error => {
        console.error('Error submitting comment:', error);
        Toast.error('提交评论失败');
      });
};


// 格式化日期方法
const formatDate = (dateStr) => {
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
};
// 页面加载时获取评论列表
onMounted(fetchComments);
// 监听路由变化以在切换页面时重新获取评论
watch(route, fetchComments);
</script>

<style scoped>

.comment-form {
  display: flex;
  align-items: center;
}

.comment-input {
  flex: 1;
  border-radius: 10px;
  background-color: #f2f2f2;
  margin-right: 10px;
}

.submit-button {
  background-color: blue;
  color: white;
}
.comment {
  border: 0 solid #ccc;
  margin-bottom: 10px;
  padding: 10px;
}

.comment-info {
  display: flex;
  align-items: center;
}

.create-time {
  margin-right: 10px;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 10px;
}

.nickname {
  font-weight: bold;
}

.content {
  margin-top: 10px;
}




.post-header {
  display: flex;
  align-items: center;
  margin: 10px 0;
}
.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}

.nickname {
  margin-left: 12px;
  font-size: 16px;
  font-weight: bold;
}

.post-content {
  padding: 16px;
}

.post-actions {
  display: flex;
  justify-content: space-between;
  padding: 16px;
}

.comment {
  display: flex;
  margin: 16px 0;
}

.comment-info {
  margin-left: 12px;
}

.content {
  margin-top: 4px;
}

.liked-icon {
  color: red;
}

</style>
